package com.ucode.crm.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ucode.crm.mapper.BusinessStatusGroupMapper;
import com.ucode.crm.mode.BusinessStatus;
import com.ucode.crm.mode.BusinessStatusGroup;
import com.ucode.crm.mode.BusinessStatusGroupDept;
import com.ucode.crm.service.BusinessStatusGroupService;
import com.ucode.crm.vo.BusinessStatusGroupVo;
import com.ucode.tool.base.ResultCodeEnum;
import com.ucode.tool.exception.UcodeServiceException;
import com.ucode.tool.util.IdentifyUtils;

import cn.hutool.core.collection.CollUtil;

@Service
public class BusinessStatusGroupServiceImpl implements BusinessStatusGroupService {

    @Autowired
    private BusinessStatusGroupMapper businessStatusGroupMapper;
    
    @Override
    @Transactional(rollbackFor=Exception.class)
    public BusinessStatusGroup insert(BusinessStatusGroupVo businessStatusGroupVo) {
        if(CollUtil.isEmpty(businessStatusGroupVo.getBusinessStatusItems())){
            throw new UcodeServiceException(ResultCodeEnum.VALIDATE_FAILED);
        }
        Date now = new Date();
        BusinessStatusGroup businessStatusGroup = new BusinessStatusGroup();
        businessStatusGroup.setId(IdentifyUtils.getDefaultSnowflakeId());
        businessStatusGroup.setCreatedTime(now);
        businessStatusGroup.setUpdatedTime(now);
        businessStatusGroup.setName(businessStatusGroupVo.getName());
        businessStatusGroup.setStatuz(businessStatusGroupVo.getStatuz());
        
        if(businessStatusGroupMapper.insert(businessStatusGroup) == 0)
            throw new UcodeServiceException(ResultCodeEnum.FAILED);
        
        List<BusinessStatus> businessStatusItems = new ArrayList<>();
        for(BusinessStatus businessStatus : businessStatusGroupVo.getBusinessStatusItems()){
            businessStatus.setId(IdentifyUtils.getDefaultSnowflakeId());
            businessStatus.setCreatedTime(now);
            businessStatus.setUpdatedTime(now);
            businessStatus.setGroupId(businessStatusGroup.getId());
        }
        
        businessStatusGroupMapper.batchSaveStatus(businessStatusItems);
        
        return businessStatusGroup;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int update(BusinessStatusGroupVo businessStatusGroupVo) {
        BusinessStatusGroup businessStatusGroup = new BusinessStatusGroup();
        businessStatusGroup.setId(businessStatusGroupVo.getId());
        businessStatusGroup.setName(businessStatusGroupVo.getName());
        businessStatusGroup.setStatuz(businessStatusGroupVo.getStatuz());
        
        if(businessStatusGroupMapper.update(businessStatusGroup) == 0)
            throw new UcodeServiceException(ResultCodeEnum.FAILED);
        
        if(CollUtil.isNotEmpty(businessStatusGroupVo.getBusinessStatusItems())){
            
            List<Long> ids = businessStatusGroupMapper.findBusinessStatuzIds(businessStatusGroup.getId());
            if(CollUtil.isNotEmpty(ids))
                businessStatusGroupMapper.batchDeleteBusinessStatus(ids);
            
            Date now = new Date();
            List<BusinessStatus> businessStatusItems = new ArrayList<>();
            for(BusinessStatus businessStatus : businessStatusGroupVo.getBusinessStatusItems()){
                businessStatus.setId(IdentifyUtils.getDefaultSnowflakeId());
                businessStatus.setCreatedTime(now);
                businessStatus.setUpdatedTime(now);
                businessStatus.setGroupId(businessStatusGroup.getId());
            }
            businessStatusGroupMapper.batchSaveStatus(businessStatusItems);
        }
        return 1;
    }

    @Override
    public int updateStatuz(Long id, Integer statuz) {
        BusinessStatusGroup businessStatusGroup = new BusinessStatusGroup();
        businessStatusGroup.setId(id);
        businessStatusGroup.setStatuz(statuz);
        return businessStatusGroupMapper.update(businessStatusGroup);
    }
    
    @Override
    public int relatedDepts(Long id, List<Long> deptIds) {
        
        /**
         * 一对多批量保存,最新的要覆盖数据库的方案：
         * 方案一、直接全部删除，在重新添加最新的，简单粗暴
         * 方案二、最新的数据跟数据库的数据对比：
         *    1.最新的没有，则代表要删除数据库里的
         *    2.最新的有,数据库里没有，则代表把最新的添加入库就可以了
         *    3.最新的跟数据库里都有，对比两个数组,得到数据库中待删除的，最新数据中没在数据库中的，分别操作
         */
        List<Long> delIds = null;
        /**********************************方案一********************************/
//        delIds = businessStatusGroupMapper.findBusinessStatusGroupDeptIds(id);
//        if(CollUtil.isNotEmpty(delIds))
//            businessStatusGroupMapper.batchDeleteGroupDept(delIds);
//        
//        if(CollUtil.isNotEmpty(deptIds)){
//            List<BusinessStatusGroupDept> list =new ArrayList<>();
//            Date now = new Date();
//            for(Long deptId : deptIds){
//                BusinessStatusGroupDept businessStatusGroupDept = new BusinessStatusGroupDept();
//                businessStatusGroupDept.setId(IdentifyUtils.getDefaultSnowflakeId());
//                businessStatusGroupDept.setDeptId(deptId);
//                businessStatusGroupDept.setGroupId(id);
//                businessStatusGroupDept.setCreatedTime(now);
//                businessStatusGroupDept.setUpdatedTime(now);
//                list.add(businessStatusGroupDept);
//            }
//            return businessStatusGroupMapper.batchSaveGroupDept(list);
//        }
        
        /**********************************方案二********************************/
        //删除数据库里的关系
        if(CollUtil.isEmpty(deptIds)){
            delIds = businessStatusGroupMapper.findBusinessStatusGroupDeptIds(id);
            return CollUtil.isNotEmpty(delIds) ? businessStatusGroupMapper.batchDeleteGroupDept(delIds) : 0;
        }
        
        List<BusinessStatusGroupDept> businessStatusGroupDepts = businessStatusGroupMapper.findBusinessStatusGroupDepts(id);
        
        //数据库中没有,则直接添加
        if(CollUtil.isEmpty(businessStatusGroupDepts)){
            List<BusinessStatusGroupDept> list =new ArrayList<>();
            Date now = new Date();
            for(Long deptId : deptIds){
                BusinessStatusGroupDept businessStatusGroupDept = new BusinessStatusGroupDept();
                businessStatusGroupDept.setId(IdentifyUtils.getDefaultSnowflakeId());
                businessStatusGroupDept.setDeptId(deptId);
                businessStatusGroupDept.setGroupId(id);
                businessStatusGroupDept.setCreatedTime(now);
                businessStatusGroupDept.setUpdatedTime(now);
                list.add(businessStatusGroupDept);
            }
            return businessStatusGroupMapper.batchSaveGroupDept(list);
        }
        
        delIds = new ArrayList<>();
        for(BusinessStatusGroupDept businessStatusGroupDept : businessStatusGroupDepts){
            if(deptIds.contains(businessStatusGroupDept.getDeptId())){
                //如果数据库里的部门,在最新部门里,则忽略添加
                deptIds.remove(businessStatusGroupDept.getDeptId());
            }else{
              //如果数据库里的部门,不在最新部门里,则需删除
                delIds.add(businessStatusGroupDept.getId());
            }
        }
        
        if(deptIds.size() > 0)
            businessStatusGroupMapper.batchDeleteGroupDept(delIds);
        
        if(deptIds.size() > 0 ){
            List<BusinessStatusGroupDept> list =new ArrayList<>();
            Date now = new Date();
            for(Long deptId : deptIds){
                BusinessStatusGroupDept businessStatusGroupDept = new BusinessStatusGroupDept();
                businessStatusGroupDept.setId(IdentifyUtils.getDefaultSnowflakeId());
                businessStatusGroupDept.setDeptId(deptId);
                businessStatusGroupDept.setGroupId(id);
                businessStatusGroupDept.setCreatedTime(now);
                businessStatusGroupDept.setUpdatedTime(now);
                list.add(businessStatusGroupDept);
            }
            return businessStatusGroupMapper.batchSaveGroupDept(list);
        }
        return 0;
    }

    @Override
    public int deleteByLogic(Long id) {
        return businessStatusGroupMapper.deleteByLogic(id);
    }

    @Override
    public int delete(Long id) {
        int i = businessStatusGroupMapper.delete(id);
        if(i > 0){
            List<Long> ids = businessStatusGroupMapper.findBusinessStatuzIds(id);
            if(CollUtil.isNotEmpty(ids))
                businessStatusGroupMapper.batchDeleteBusinessStatus(ids);
        }
        return i;
    }

    @Override
    public BusinessStatusGroup findById(Long id) {
        return businessStatusGroupMapper.findById(id);
    }

    @Override
    public List<BusinessStatusGroup> findByIds(List<Long> ids) {
        return businessStatusGroupMapper.findByIds(ids);
    }
    
    @Override
    public List<BusinessStatus> findBusinessStatuzs(Long groupId) {
        return businessStatusGroupMapper.findBusinessStatuzs(groupId);
    }
    
    @Override
    public List<BusinessStatusGroup> findDeptValidBusinessStatusGroup(List<Long> depteIds) {
        return businessStatusGroupMapper.findDeptValidBusinessStatusGroup(depteIds);
    }

}
